//==================客户端======================

const dataKit = require( "./util/dataKit")
const dateKit = require( "./util/dateKit")
const clientService = require( "./util/clientService");
const util = require("./util/util");

/**
 * 客户端(用户登录)
 * @param {} context 
 */
exports.login = async (context) => {
  const {openId} = context;
  var {avatar,userNick} = context.data;
  if(!avatar){
        return {code:500,msg:"avatar是必须的"};
  }
  if(!userNick){
        return {code:500,msg:"userNick是必须的"};
  }
  var userInfo = await context.cloud.db.collection('user_info').find({openId:openId},{limit:1});
  userInfo = userInfo.length>0?userInfo[0]:null;
  if(!userInfo){
    userInfo = {
      openId:openId,
      isFirstLogin:true,
      drawNum:0,
      createTime:dateKit.getCurrentDateTime()
    }
  }else{
    userInfo.isFirstLogin = false;
  }
  userInfo.userNick = userNick,
  userInfo.avatar = avatar,
  userInfo.loginTime = dateKit.getCurrentDateTime();
  const result = await dataKit.insertOrUpdate(context,'user_info',userInfo);
  return  {code:200,msg:'登录成功',data:userInfo};
}

/**
 * 测试接口
 * @param {} context 
 */
exports.ceshi = async (context) => {
   const {openId} = context;
  //  const result = await context.cloud.db.collection('task_record').aggregate([
  //     { $match: {openId:openId,createTime: dateKit.getTodayCondiction(),type:{$in:['inviteToMember','inviteToFollow','share']}} },
  //     {
  //       $group: {
  //           _id: "$type",
  //           count: { $sum: 1 }
  //       }
  //     }
  // ]);
  // var list = await context.cloud.db.collection('task_record').aggregate(
  //   [
      
  //     { $match:{openId:openId,type:{$in:['follow','collectProduct','kagaProduct']}}},
  //     {$project: {_id: 1,type:1,remark:1}},
  //     {
  //       $group: {
  //           _id: "$productId"
          
  //       }
  //     }
  //   ]
  // );
  // var drawItem = {};
  // drawItem.level = 9;
  // var aa = 0;
  // if(drawItem != null && drawItem.level != 9){
  //   aa = 777;
  // }
  // let probability = parseFloat(25.5) / 100;
  // let cc = Math.floor(Math.random() * (5 - 0)) + 0
  // if(cc == 0){
  //   aa = '风不会停息';
  // }

  // let hh = '哈哈';
  // if(8 >= 0 && 8 < 8 + 1){
  //   hh = '风不会停息';
  // }
  //let aa = 'MD00XRV0' + 0;
  //var send = await clientService.sendBenefit(context,openId,'2e7cb3dfef2b43d4872ecaa4530acbb6',7772,'AAEY9ZClANkaeDgj-XGzrN1s')
  //await dataKit.deleteMany(context,'prize_log',{openId:openId})
  return {code:200,msg:'查询成功',data:send}
}

/**
 * 获取用户信息
 * @param {} context 
 */
exports.getUserInfo = async (context) => {
  const {openId} = context;
  var userInfo = await clientService.getUserByOpenId(context,openId);
  //防止null数据前端不校验报错
  userInfo = userInfo==null?{}:userInfo;
  return {code:200,msg:'查询成功',data:userInfo}
}

// /**
//  * 任务列表
//  * @param {} context 
//  */
// exports.taskList = async (context) => {
//   const {openId} = context;
//   var taskList = [];
//   var list = await context.cloud.db.collection('task_record').aggregate(
//     [
//      { $match:{openId:openId,type:{$in:['follow','collectProduct','kagaProduct']}}}
//     ]
//   );
//   for (var a = 0;a < 3;a++) {
//     var task = {num:0,status:0,goodsList:[]}
//     switch (a) {
//       case 0:
//         task.name = 'follow';
//         task.msg = '关注店铺';
//       break;
//       case 1:
//         task.name = 'collectProduct';
//         task.msg = '收藏商品';
//       break;
//       case 2:
//         task.name = 'kagaProduct';
//         task.msg = '加购商品';
//       break;
//     }
//     taskList[a] = task;
//   }
//   for(var b = 0;b < list.length;b++){
//     var taskData = list[b];
//     switch (taskData.type) {
//       case 'follow':
//         taskList[0].status = 1;
//         taskList[0].num++;
//       break;
//       case 'collectProduct':
//         taskList[1].goodsList.push(taskData);
//         taskList[1].num++;
//         if(taskList[1].num == 3){
//           taskList[1].status = 1;
//         }
//       break;
//       case 'kagaProduct':
//         taskList[2].goodsList.push(taskData);
//         taskList[2].num++;
//         if(taskList[2].num == 3){
//           taskList[2].status = 1;
//         }
//       break;
//     }
//   }
//   return {code:200,msg:'查询成功',data:taskList}
// }

/**
 * 任务列表
 * @param {} context 
 */
exports.taskList = async (context) => {
  const {openId} = context;
  var taskList = [];
  var list = await context.cloud.db.collection('task_record').aggregate([{ $match:{openId:openId,type:{$in:['follow','collectProduct','kagaProduct']}}}]);
  for (var a = 0;a < 3;a++) {
    var task = {status:0}
    switch (a) {
      case 0:
        task.name = 'follow';
        task.msg = '关注店铺';
      break;
      case 1:
        task.name = 'collectProduct';
        task.msg = '收藏商品';
      break;
      case 2:
        task.name = 'kagaProduct';
        task.msg = '加购商品';
      break;
    }
    taskList[a] = task;
  }
  for(var b = 0;b < list.length;b++){
    var taskData = list[b];
    switch (taskData.type) {
      case 'follow':
        taskList[0].status = 1;
      break;
      case 'collectProduct':
        taskList[1].status = 1;
      break;
      case 'kagaProduct':
        taskList[2].status = 1;
      break;
    }
  }
  return {code:200,msg:'查询成功',data:taskList}
}

/**
 * 关注
 * @param {*} context 
 */
exports.follow = async (context) => {
  const {openId} = context;
  const result = await clientService.follow(context,openId);
  return result;
}

/**
 * 收藏商品
 * @param {*} context 
 */
// exports.collectProduct = async (context) => {
//   const {openId} = context;
//   const {productId} = context.data;
//   const result = await clientService.collectProduct(context,openId,productId);
//   return result;
// }

/**
 * 收藏商品
 * @param {*} context 
 */
exports.collectProduct = async (context) => {
  const {openId} = context;
  const result = await clientService.collectProduct(context,openId);
  return result;
}

/**
 * 加购商品
 * @param {*} context 
 */
// exports.kagaProduct = async (context) => {
//   const {openId} = context;
//   const {productId} = context.data;
//   const result = await clientService.kagaProduct(context,openId,productId);
//   return result;
// }

/**
 * 加购商品
 * @param {*} context 
 */
exports.kagaProduct = async (context) => {
  const {openId} = context;
  const result = await clientService.kagaProduct(context,openId);
  return result;
}


/**
 * 抽奖接口
 * @param {*} context 
 */
exports.luckyDraw = async (context) => {
  const {openId} = context;
  var userInfo = await clientService.getUserByOpenId(context,openId);
  if(userInfo.drawNum  <= 0){
    return {code:500,msg:'用户暂无抽奖次数',data:{}}
  }else{
    //减掉抽奖次数
    await dataKit.update(context, "user_info", {openId:openId},{drawNum:userInfo.drawNum - 1});
  }
  
  let mid = 0;//中间值
  let random = Math.floor(Math.random() * (10000 - 0)) + 0//0到100随机数
  let drawItem = null;
  let level = 9;
  //取这段时间的奖品(及规则)
  var prizeList = await context.cloud.db.collection('prize').find({startTime: {$lt:dateKit.getCurrentDateTime()},endTime:{$gt:dateKit.getCurrentDateTime()}},{sort: {level: 1}})
  for (gift of prizeList) {
    let probability = await parseFloat(gift.probability);
    if (random >= mid && random < mid + probability) {
      // 满足条件则将产品信息进行赋值
      drawItem = gift;
      level = drawItem.level;
      break;
    }
    mid = mid + probability;
  }

  var prizeId = util.uuid();//随机奖品id
  if(level != 9){
    if(level == 2){
      var send = await clientService.sendBenefit(context,openId,'f43622cd508944a793fd8f6e78c0194e',7772,'AAEY9ZClANkaeDgj-XGzrN1s')
      if(send.success == 200){
        //乐观锁控制 --start
        prize = await dataKit.findOne(context,"prize",{_id:drawItem._id});
        if(drawItem.version == prize.version && prize.num > 0){
          //减掉对应库存(修改乐观锁版本号) 编号+1
          await dataKit.update(context, "prize", {_id:prize._id},{num:prize.num - 1,version:prize.version + 1,number:prize.number + 1});
          //生成抽奖记录
          prizeLogDate = {
            name:prize.name,//奖品名称
            number:prize.prefix + prize.number,//奖品骗号
            prizeId:prizeId,//奖品id
            level:prize.level,//奖品等级
            logo:prize.logo,//奖品图片
            type:prize.type,//奖品类型：0-虚拟奖 1-实物奖
            openId:openId,
            userNick:userInfo.userNick,//用户昵称
            adress:'',//用户地址
            isReceived:true,//是否已领取: true-是 false-否
            isWinPrize:true,//是否中奖: true-是 false-否
            userName:'',//收货人姓名
            phone:'',//收货人电话
            createTime:dateKit.getCurrentDateTime(),//抽奖时间
          }
          await dataKit.insertOne(context,'prize_log',prizeLogDate);
          return {code:200, msg:'抽奖成功', data:{giftName:prize.name,giftIndex:prize.level,giftUrl:'',giftNumber:'',prizeId:prizeId}}
        }
      }
    }else if(level == 6){
      var send = await clientService.sendBenefit(context,openId,'2e7cb3dfef2b43d4872ecaa4530acbb6',7776,'AAEY9ZClANkaeDgj-XGzrN1s')
      if(send.success == 200){
        //乐观锁控制 --start
        prize = await dataKit.findOne(context,"prize",{_id:drawItem._id});
        if(drawItem.version == prize.version && prize.num > 0){
          //减掉对应库存(修改乐观锁版本号)
          await dataKit.update(context, "prize", {_id:prize._id},{num:prize.num - 1,version:prize.version + 1});
          //生成抽奖记录
          prizeLogDate = {
            name:prize.name,//奖品名称
            number:'',//奖品骗号
            prizeId:prizeId,//奖品id
            level:prize.level,//奖品等级
            logo:prize.logo,//奖品图片
            type:prize.type,//奖品类型：0-虚拟奖 1-实物奖
            openId:openId,
            userNick:userInfo.userNick,//用户昵称
            adress:'',//用户地址
            isReceived:true,//是否已领取: true-是 false-否
            isWinPrize:true,//是否中奖: true-是 false-否
            userName:'',//收货人姓名
            phone:'',//收货人电话
            createTime:dateKit.getCurrentDateTime(),//抽奖时间
          }
          await dataKit.insertOne(context,'prize_log',prizeLogDate);
          return {code:200, msg:'抽奖成功', data:{giftName:prize.name,giftIndex:prize.level,giftUrl:'',giftNumber:'',prizeId:prizeId}}
        }
      }
    }else if(level == 7){
      var send = await clientService.sendBenefit(context,openId,'ad34f66111714af2a5f02bbf78b9fbc1',7777,'AAEY9ZClANkaeDgj-XGzrN1s')
      if(send.success == 200){
        //乐观锁控制 --start
        prize = await dataKit.findOne(context,"prize",{_id:drawItem._id});
        if(drawItem.version == prize.version && prize.num > 0){
          //减掉对应库存(修改乐观锁版本号)
          await dataKit.update(context, "prize", {_id:prize._id},{num:prize.num - 1,version:prize.version + 1});
          //生成抽奖记录
          prizeLogDate = {
            name:prize.name,//奖品名称
            number:'',//奖品骗号
            prizeId:prizeId,//奖品id
            level:prize.level,//奖品等级
            logo:prize.logo,//奖品图片
            type:prize.type,//奖品类型：0-虚拟奖 1-实物奖
            openId:openId,
            userNick:userInfo.userNick,//用户昵称
            adress:'',//用户地址
            isReceived:true,//是否已领取: true-是 false-否
            isWinPrize:true,//是否中奖: true-是 false-否
            userName:'',//收货人姓名
            phone:'',//收货人电话
            createTime:dateKit.getCurrentDateTime(),//抽奖时间
          }
          await dataKit.insertOne(context,'prize_log',prizeLogDate);
          return {code:200,msg:'抽奖成功！',data:{giftName:prize.name,giftIndex:prize.level,giftUrl:'',giftNumber:'',prizeId:prizeId}}
        }
      }
    }else if(level == 8){
      var send = await clientService.sendBenefit(context,openId,'f316a8c8c17045d8ba3e23e65f2fa6d8',7778,'AAE_9ZClANkaeDgj-XEI2V4Q')
      if(send.success == 200){
        //乐观锁控制 --start
        prize = await dataKit.findOne(context,"prize",{_id:drawItem._id});
        if(drawItem.version == prize.version && prize.num > 0){
          //减掉对应库存(修改乐观锁版本号)
          await dataKit.update(context, "prize", {_id:prize._id},{num:prize.num - 1,version:prize.version + 1});
          //生成抽奖记录
          prizeLogDate = {
            name:prize.name,//奖品名称
            number:'',//奖品骗号
            prizeId:prizeId,//奖品id
            level:prize.level,//奖品等级
            logo:prize.logo,//奖品图片
            type:prize.type,//奖品类型：0-虚拟奖 1-实物奖
            openId:openId,
            userNick:userInfo.userNick,//用户昵称
            adress:'',//用户地址
            isReceived:true,//是否已领取: true-是 false-否
            isWinPrize:true,//是否中奖: true-是 false-否
            userName:'',//收货人姓名
            phone:'',//收货人电话
            createTime:dateKit.getCurrentDateTime(),//抽奖时间
          }
          await dataKit.insertOne(context,'prize_log',prizeLogDate);
          return {code:200,msg:'抽奖成功！',data:{giftName:prize.name,giftIndex:prize.level,giftUrl:'',giftNumber:'',prizeId:prizeId}}
        }
      }
    }else{
      //乐观锁控制 --start
      prize = await dataKit.findOne(context,"prize",{_id:drawItem._id});
      if(drawItem.version == prize.version && prize.num > 0){
        //减掉对应库存(修改乐观锁版本号)
        await dataKit.update(context, "prize", {_id:prize._id},{num:prize.num - 1,version:prize.version + 1,number:prize.number + 1});
        //生成抽奖记录
        prizeLogDate = {
          name:prize.name,//奖品名称
          number:prize.prefix + prize.number,//奖品骗号
          prizeId:prizeId,//奖品id
          level:prize.level,//奖品等级
          logo:prize.logo,//奖品图片
          type:prize.type,//奖品类型：0-虚拟奖 1-实物奖
          openId:openId,
          userNick:userInfo.userNick,//用户昵称
          adress:'',//用户地址
          isReceived:false,//是否已领取: true-是 false-否
          isWinPrize:true,//是否中奖: true-是 false-否
          userName:'',//收货人姓名
          phone:'',//收货人电话
          createTime:dateKit.getCurrentDateTime(),//抽奖时间
        }
        await dataKit.insertOne(context,'prize_log',prizeLogDate);
        return {code:200,msg:'抽奖成功!',data:{giftName:prize.name,giftIndex:prize.level, giftUrl:'',giftNumber:prize.prefix + prize.number,prizeId:prizeId}}
      }
    }
    //--end
  }

  //生成不中奖的抽奖记录
  newPrizeList = await context.cloud.db.collection('prize').find({level:9,startTime: {$lt:dateKit.getCurrentDateTime()},endTime:{$gt:dateKit.getCurrentDateTime()}},{
    limit: 1,
  })
  prize = newPrizeList[0];
  prizeLogDate = {
          name:'good luck',//奖品名称
          number:'',//奖品骗号
          prizeId:prizeId,//奖品id
          level:prize.level,//奖品等级
          logo:prize.logo,//奖品图片
          type:prize.type,//奖品类型：0-虚拟奖 1-实物奖
          openId:openId,
          userNick:userInfo.userNick,//用户昵称
          adress:'',//用户地址
          isReceived:false,//是否已领取: true-是 false-否
          isWinPrize:false,//是否中奖: true-是 false-否
          userName:'',//收货人姓名
          phone:'',//收货人电话
          createTime:dateKit.getCurrentDateTime(),//抽奖时间
  }
  await dataKit.insertOne(context,'prize_log',prizeLogDate);
  return {code:200,msg:'抽奖成功!', data:{giftName:'good luck',giftIndex:9,giftUrl:'',giftNumber:'',prizeId:prizeId}}
}

/**
 * 获取用户奖品列表
 * @param {} context 
 */
exports.prizeList = async (context) => {
  const {openId} = context;
  var prizeList = await clientService.getPrizeLogByopenIdList(context,openId);
  return {code:200,msg:"查询成功",data:prizeList}
}

/**
 *  填写我的收货地址
 * @param {} context 
 */
exports.address = async (context) => {
  const {provinceName,cityName,countyName,streetName,streetCode,detailInfo,id,name,telNumber} = context.data;
  var address = provinceName + cityName + countyName + streetName + streetCode + detailInfo;
  const returt = await dataKit.update(context, "prize_log", {prizeId:id},{adress:address,userName:name,phone:telNumber,isReceived:true});
  return {code:200,msg:"操作成功",data:address}
}


/**
 * 埋点
 * @param {*} context 
 */
exports.buriedPoint = async (context) => {
    const userData = context.data;
    const {openId} = context;
    //首次登陆
    await clientService.buriedPoint(context,openId,userData)
    return {code:200,msg:"埋点成功",data:userData};
}

/**
 * 埋点查询
 * @param {*} context 
 */
exports.getburiedPointList = async (context) => {
  var list = await clientService.getburiedPointList(context);
  return {code:200,msg:"查询成功",data:list};
}





